<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>贪吃蛇游戏</title>
<style>
  #gameCanvas {
    background-color: #000;
    display: block;
    margin: auto;
  }
</style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<script>
  const canvas = document.getElementById('gameCanvas');
  const ctx = canvas.getContext('2d');

  const gridSize = 20;
  const tileCount = canvas.width / gridSize;

  let snake = [{x: 10, y: 10}];
  let food = {x: 15, y: 15};
  let dx = 0;
  let dy = 0;

  function randomizeFood() {
    food.x = Math.floor(Math.random() * tileCount);
    food.y = Math.floor(Math.random() * tileCount);
  }

  function draw() {
    ctx.fillStyle = 'black';
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    ctx.fillStyle = 'lime';
    snake.forEach((part, index) => {
      if (index === 0) {
        ctx.fillStyle = 'green';
      }
      ctx.fillRect(part.x * gridSize, part.y * gridSize, gridSize, gridSize);
    });

    ctx.fillStyle = 'red';
    ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize, gridSize);
  }

  function update() {
    const head = {x: snake[0].x + dx, y: snake[0].y + dy};
    snake.unshift(head);

    if (snake[0].x === food.x && snake[0].y === food.y) {
      randomizeFood();
    } else {
      snake.pop();
    }

    // 检查是否撞墙
    if (snake[0].x < 0 || snake[0].x >= tileCount || snake[0].y < 0 || snake[0].y >= tileCount) {
      clearInterval(gameLoop);
      alert('游戏结束！');
    }

    // 检查是否撞到自己
    for (let i = 4; i < snake.length; i++) {
      if (snake[i].x === snake[0].x && snake[i].y === snake[0].y) {
        clearInterval(gameLoop);
        alert('游戏结束！');
      }
    }
  }

  function changeDirection(event) {
    const LEFT_KEY = 37;
    const RIGHT_KEY = 39;
    const UP_KEY = 38;
    const DOWN_KEY = 40;

    const keyPressed = event.keyCode;
    const goingUp = dy === -1;
    const goingDown = dy === 1;
    const goingRight = dx === 1;
    const goingLeft = dx === -1;

    if (keyPressed === LEFT_KEY && !goingRight) {
      dx = -1;
      dy = 0;
    }

    if (keyPressed === UP_KEY && !goingDown) {
      dx = 0;
      dy = -1;
    }

    if (keyPressed === RIGHT_KEY && !goingLeft) {
      dx = 1;
      dy = 0;
    }

    if (keyPressed === DOWN_KEY && !goingUp) {
      dx = 0;
      dy = 1;
    }
  }

  document.addEventListener('keydown', changeDirection);

  let gameLoop = setInterval(function() {
    update();
    draw();
  }, 100);
</script>
</body>
</html>
